const express = require("express");

const app = express();
// 1-Get
app.get("/server", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //设置响应体
  response.send("hello Ajax");
});

app.get("/cors", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5500");
  //设置响应体
  response.send("hello Ajax");
});

app.get("/delay", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //设置响应体
  setTimeout(() => {
    response.send("hello Ajax");
  }, 3000);
});

app.all("/jquery", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //指定以情头
  response.setHeader("Access-Control-Allow-Headers", "*");
  //设置响应体
  const data = { name: "尚硅谷" };
  response.send(JSON.stringify(data));
});

app.all("/axios", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //指定以情头
  response.setHeader("Access-Control-Allow-Headers", "*");
  //设置响应体
  const data = { name: "axios" };
  response.send(JSON.stringify(data));
});

app.all("/fetch", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //指定以情头
  response.setHeader("Access-Control-Allow-Headers", "*");
  //设置响应体
  const data = { name: "fetch" };
  response.send(JSON.stringify(data));
});

app.all("/checkname", (request, response) => {
  // //允许跨域
  // response.setHeader("Access-Control-Allow-Origin", "*");
  // //指定以情头
  // response.setHeader("Access-Control-Allow-Headers", "*");
  //设置响应体
  const data = { exist: "1", msg: "用户名已存在" };
  let str = JSON.stringify(data);
  //end
  response.end(`handle(${str})`);
});

app.all("/jqueryjsonp", (request, response) => {
  // //允许跨域
  // response.setHeader("Access-Control-Allow-Origin", "*");
  // //指定以情头
  // response.setHeader("Access-Control-Allow-Headers", "*");
  //设置响应体
  const data = { name: "wxy", msg: "哈哈" };
  let str = JSON.stringify(data);
  let cb = request.query.callback;
  //end
  response.end(`${cb}(${str})`);
});

// 2-Post
app.all("/server", (request, response) => {
  //允许跨域
  response.setHeader("Access-Control-Allow-Origin", "*");
  //响应头
  response.setHeader("Access-Control-Allow-Headers", "*");

  const data = {
    name: "hhy",
  };

  //设置响应体
  response.send(JSON.stringify(data));
});

app.listen(8000, () => {
  console.log("服务已经启动，8000端口监听中");
});
